<template>
  <div class="hjexcel-box" ref="hjexcel">
    <div class="hjexcel-box_">
      <!-- <div class="hjexcel-form">
        <div>
          <span>文件地址:</span>
          <el-input
            style="margin-bottom: 10px"
            v-model="fileUrl"
            placeholder="请输入"
          ></el-input>
          <el-button type="primary" @click="initTable">1.加载表格</el-button>
          <el-button type="primary" @click="getBindKey">
            {{ bindkey ? "2.清空绑定" : "2.绑定输入框" }}
          </el-button>
          <el-button type="primary" @click="getKeyValue"
            >3.获取填写数据提交给后端</el-button
          >
          <el-button type="primary" @click="setLastCellValue"
            >4.绑定上一次的输入值</el-button
          >
        </div>
        <div style="margin-top: 10px">
          <el-input v-model="methodFunStr"></el-input>
          <el-button type="primary" @click="carryOut">10.执行方法</el-button>
          <el-button type="primary" @click="disabledInput"
            >11.禁止编辑</el-button
          >
        </div>
      </div> -->
      <div class="hjexcel-view" id="hjexcel-view" />
    </div>
  </div>
</template>
<script>
export default {
  name: "HJExcel",
  data() {
    return {
      bindkey: null,
      fileUrl: `${location.origin}/file-res/1730452402816.xlsx`, // "https://test-safety.hj-tec.com/image/2024/1104/2f42e304ac29488dacaf77aff6261fb3/1730704216700.xlsx",
      methodFunStr: null,
      currentCell: null,
    };
  },
  mounted() {
    this.initTable();
  },
  methods: {
    initTable() {
      let loadUrl = null;
      if (!this.fileUrl && localStorage.getItem("excelJson")) {
        loadUrl = JSON.parse(localStorage.getItem("excelJson"));
      } else if (!this.fileUrl || !this.fileUrl.includes("http")) {
        return this.$message.warning("请输入服务器文件地址");
      } else if (!this.fileUrl.includes("xlsx")) {
        return this.$message.warning("只支持xlsx格式");
      }
      this.clearBindCellValue();
      this.cleanCellInputStyle();
      this.bindkey = null;
      this.create(loadUrl);
    },
    getBindKey() {
      if (this.bindkey) {
        this.clearBindCellValue();
        this.cleanCellInputStyle();
        this.bindkey = null;
        return this.$message.success("已清空绑定");
      }

      let obj = {};
      const sheets = window.luckysheet.getAllSheets();
      sheets?.forEach((sheet, index) => {
        const sheetData = sheet.celldata;
        sheetData.forEach((item) => {
          if (item.v.m && item.v.m.includes("form.")) {
            obj[`${index}-${item.r}_${item.c}`] = item.v.m;
          }
        });
      });
      if (!Object.keys(obj)?.length) return this.$message.warning("请填写");
      this.bindkey = obj;
      this.$message.success("已完成绑定");
      alert(JSON.stringify(this.bindkey));
      this.setCellInputStyle();
      this.clearBindCellValue();
      this.disabledInput();
    },
    setCellInputStyle() {
      for (let key in this.bindkey) {
        const order = parseInt(key.split("-")[0]);
        const pos = key.split("-")[1].split("_");
        const r = pos[0];
        const c = pos[1];
        window.luckysheet.setCellFormat(r, c, "bg", "#e9e9e9", { order });
      }
    },
    cleanCellInputStyle() {
      for (let key in this.bindkey) {
        const order = parseInt(key.split("-")[0]);
        const pos = key.split("-")[1].split("_");
        const r = pos[0];
        const c = pos[1];
        window.luckysheet.setCellFormat(r, c, "bg", "#ffffff", { order });
      }
    },
    clearBindCellValue() {
      for (let key in this.bindkey) {
        const order = parseInt(key.split("-")[0]);
        const pos = key.split("-")[1].split("_");
        const r = pos[0];
        const c = pos[1];
        window.luckysheet.setCellValue(r, c, "", { order });
        window.luckysheet.setCellFormat(r, c, "bg", "#b7b7b7", { order });
      }
    },
    getKeyValue() {
      if (!this.bindkey) {
        return this.$message.warning("请先绑定输入框");
      }
      const cellDataArr = window.luckysheet.getAllSheets();
      let obj = {};
      cellDataArr?.forEach((sheet, index) => {
        const sheetData = sheet.celldata;
        sheetData.forEach((item) => {
          const key = `${index}-${item.r}_${item.c}`;
          if (item.v.m && key in this.bindkey) {
            obj[this.bindkey[key]] = item.v.m;
          }
        });
      });

      alert(JSON.stringify(obj));
    },
    setLastCellValue() {
      const obj = {
        "0-4_4": "测试工程",
        "0-6_2": "测试单位",
        "0-8_1": "请立即整改，并于3天内提交报告",
        "0-14_6": "2024-10-11 11",
        "0-14_16": "所有",
        "0-16_1": "请立即整改！！！！，并于3天内提交报告！！！",
        "0-22_22": "测试",
        "0-24_22": "张三",
        "0-25_22": "24-10-31",
      };
      for (let key in obj) {
        const order = parseInt(key.split("-")[0]);
        const pos = key.split("-")[1].split("_");
        const r = pos[0];
        const c = pos[1];
        try {
          window.luckysheet.setCellValue(r, c, obj[key], { order });
        } catch (e) {
          alert("请先加载表格");
        }
      }
    },
    carryOut() {
      try {
        const val = eval(this.methodFunStr);
        console.log(val);
      } catch (e) {
        alert("请输入正确的方法");
      }
    },
    create(loadUrl) {
      let vm = this;
      const defaultConfig = {
        lang: "zh",
        showtoolbar: true, // 是否显示工具栏
        showinfobar: false, // 是否显示顶部信息栏
        showstatisticBar: false, // 是否显示底部计数栏
        sheetBottomConfig: false, // sheet页下方的添加行按钮和回到顶部按钮配置
        allowEdit: true, // 是否允许前台编辑
        enableAddRow: false, // 是否允许增加行
        enableAddCol: false, // 是否允许增加列
        sheetFormulaBar: false, // 是否显示公式栏
        enableAddBackTop: false, // 返回头部按钮
        showsheetbar: true, // 是否显示底部sheet页按钮
        // 自定义配置底部sheet页按钮
        showsheetbarConfig: {
          add: false,
          menu: false,
          zoom: true,
        },
        showtoolbarConfig: {
          undoRedo: false, //撤销重做，注意撤消重做是两个按钮，由这一个配置决定显示还是隐藏
          paintFormat: false, //格式刷
          currencyFormat: false, //货币格式
          percentageFormat: false, //百分比格式
          numberDecrease: false, // '减少小数位数'
          numberIncrease: false, // '增加小数位数
          moreFormats: false, // '更多格式'
          font: false, // '字体'
          fontSize: false, // '字号大小'
          bold: false, // '粗体 (Ctrl+B)'
          italic: false, // '斜体 (Ctrl+I)'
          strikethrough: false, // '删除线 (Alt+Shift+5)'
          underline: false, // '下划线 (Alt+Shift+6)'
          textColor: false, // '文本颜色'
          fillColor: false, // '单元格颜色'
          border: false, // '边框'
          mergeCell: false, // '合并单元格'
          horizontalAlignMode: false, // '水平对齐方式'
          verticalAlignMode: false, // '垂直对齐方式'
          textWrapMode: false, // '换行方式'
          textRotateMode: false, // '文本旋转方式'
          image: true, // '插入图片'
          link: false, // '插入链接'
          chart: false, // '图表'（图标隐藏，但是如果配置了chart插件，右击仍然可以新建图表）
          postil: false, //'批注'
          pivotTable: false, //'数据透视表'
          function: false, // '公式'
          frozenMode: false, // '冻结方式'
          sortAndFilter: false, // '排序和筛选'
          conditionalFormat: false, // '条件格式'
          dataVerification: false, // '数据验证'
          splitColumn: false, // '分列'
          screenshot: false, // '截图'
          findAndReplace: false, // '查找替换'
          protection: false, // '工作表保护'
          print: false, // '打印'
          exportXlsx: false, // '导出'
        },
        cellRightClickConfig: {
          copy: false, // 复制
          copyAs: false, // 复制为
          paste: false, // 粘贴
          insertRow: false, // 插入行
          insertColumn: false, // 插入列
          deleteRow: false, // 删除选中行
          deleteColumn: false, // 删除选中列
          deleteCell: false, // 删除单元格
          hideRow: false, // 隐藏选中行和显示选中行
          hideColumn: false, // 隐藏选中列和显示选中列
          rowHeight: false, // 行高
          columnWidth: false, // 列宽
          clear: false, // 清除内容
          matrix: false, // 矩阵操作选区
          sort: false, // 排序选区
          filter: false, // 筛选选区
          chart: false, // 图表生成
          image: false, // 插入图片
          link: false, // 插入链接
          data: false, // 数据验证
          cellFormat: false, // 设置单元格格式
        },
        uploadImage: function () {
          return new Promise(function (reject, resolve) {
            if (vm.currentCell.mc.r == 20 && vm.currentCell.mc.c == 22) {
              setTimeout(() => {
                window.luckysheet.insertImage(
                  "https://qhstaticssl.kujiale.com/newt/102042/image/png/1632383292602/A103232512ABF4365C5236FE2263E21C.png",
                  { autoSize: true, rowIndex: 20, colIndex: 22, order: 0 }
                );
                resolve(null);
              }, 500);
            } else {
              vm.$message.warning("当前单元格不可以插入图片");
              reject(false);
            }
          });
        },
        imageOperationConfig: {
          move: false, // 移动
        },
        hook: {
          cellMousedownBefore: (cell, position) => {
            console.log(cell.v);
            console.log(position);
            vm.currentCell = cell;
            const { r, c } = position;
            if (r === 20 && c === 22) {
              vm.$message.warning("请上传图片");
              window.$("#luckysheet-insertImg-btn-title").click();
            } else if (["☑", "□"].includes(cell.v)) {
              setTimeout(() => {
                window.luckysheet.exitEditMode();
              }, 150);
            }
          },
          cellMousedown: (cell, position) => {
            console.log(cell);
            console.log(position);
            console.log(cell.v);
            if (["☑", "□"].includes(cell.v)) {
              window.luckysheet.setCellValue(
                position.r,
                position.c,
                cell.v === "☑" ? "□" : "☑",
                { order: 0 }
              );
            }
          },
        },
      };

      this.isMaskShow = true;

      if (loadUrl) {
        return window.luckysheet.create({
          container: "hjexcel-view", //luckysheet is the container id
          data: loadUrl, // 接口地址
          ...defaultConfig,
        });
      }

      window.LuckyExcel.transformExcelToLuckyByUrl(
        this.fileUrl,
        "test",
        (exportJson) => {
          console.log(exportJson);
          if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            alert(
              "Failed to read the content of the excel file, currently does not support xls files!"
            );
            return;
          }

          this.isMaskShow = false;
          window.luckysheet.destroy();

          window.luckysheet.create({
            container: "hjexcel-view", //luckysheet is the container id
            showinfobar: false,
            data: exportJson.sheets,
            title: exportJson.info.name,
            userInfo: exportJson.info.name.creator,
            ...defaultConfig,
          });
        }
      );
    },
    disabledInput() {
      const cfg = window.luckysheet.getconfig();
      const defaultRangeConfig = {
        sheet: 0,
        name: "area", //名称
        password: "", //密码
        hintText: "", //提示文字
        algorithmName: "None", //加密方案：MD2,MD4,MD5,RIPEMD-128,RIPEMD-160,SHA-1,SHA-256,SHA-384,SHA-512,WHIRLPOOL
        saltValue: null, //密码解密的盐参数，为一个自己定的随机数值
      };
      const allowRangeList = [];
      for (let key in this.bindkey) {
        const pos = key.split("-")[1].split("_");
        const r = +pos[0];
        const c = +pos[1];
        const sheetData =
          window.luckysheet.getAllSheets()[key.split("-")[0]].celldata;
        const item = sheetData.find((item) => item.r == r && item.c == c);
        if (!item) return;
        const r2 = r + +item.v.mc.rs - 1;
        const c2 = c + +item.v.mc.cs - 1;

        const txt = window.luckysheet.getTxtByRange({
          column: [c, c2],
          row: [r, r2],
        });
        console.log(txt);
        allowRangeList.push({
          ...defaultRangeConfig,
          sqref: txt,
        });
      }

      window.luckysheet.setConfig(
        {
          ...cfg,
          authority: {
            sheet: 1,
            allowRangeList,
          },
        },
        {
          order: 0,
        }
      );
    },
  },
};
</script>

<style>
.luckysheet-modal-dialog {
  /* pointer-events: none; */
}
.luckysheet-modal-dialog-slider-imageCtrl {
  display: none !important;
}
.hjexcel-box {
  width: 100vw;
  height: 100vh;
  display: flex;
}
.hjexcel-box_ {
  width: 100%;
  height: 100%;
  display: flex;
}
.hjexcel-form {
  flex: 1;
  height: 100%;
  padding: 10px;
}
.hjexcel-view {
  flex: 1;
  height: 100%;
}
</style>
